﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Script.Serialization;
using Xenta.Attributes;
using Xenta.Entities;
using Xenta.Utils;

namespace Xenta.Plugins
{
    [Dependency("3f2535fc-aeb1-434d-9b52-3c8b290daae7", 
        Name = "Open Exchange Rates Provider")]
    public sealed class OpenExchangeRatesProvider : ICurrencyRateProvider
    {
        #region Constants

        public const string OER_URL = @"http://openexchangerates.org/latest.json";

        #endregion

        #region Methods

        public void GetRates(IDictionary<CurrencyEntity, Decimal> rates)
        {
            using(var client = new WebClient())
            {
                string jsonDataStr = client.DownloadString(OER_URL);
                if(String.IsNullOrWhiteSpace(jsonDataStr))
                    throw Err.Of(this).No("Data").Ex();

                var jss = new JavaScriptSerializer();
                var jsonData = jss.DeserializeObject(jsonDataStr) 
                    as Dictionary<String, Object>;

                if(!jsonData.ContainsKey("rates"))
                    throw Err.Of(this).No("Rates").Ex();

                foreach(var i in jsonData["rates"] as Dictionary<String, Object>)
                {
                    var currency = rates.Keys.SingleOrDefault(x => x.Code.Equals(i.Key));
                    if(currency == null)
                        continue;

                    rates[currency] = Convert.ToDecimal(i.Value);
                }
            }
        }

        #endregion
    }
}
